package com.sx.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : AdinZ  1454269@qq.com
 * @Description: TODO
 * @date Date : 2018年12月18日 15:33
 **/

public class TaskExecutor {
    private static TaskExecutor taskExecutor = null;
    private BlockingQueue<Runnable> queue ;
    private ThreadPoolExecutor executor;
    private static int corePoolSize=100;
    private static int maximumPoolSize=200;
    private static long keepAliveTime=2;
    public  void shutdown() {
        if(executor != null) {
            executor.shutdown();
            executor = null;
        }
    }

    public static TaskExecutor getInstance(){
        if(taskExecutor==null){
            synchronized (TaskExecutor.class) {
                taskExecutor = new TaskExecutor();
            }
        }
        return taskExecutor;
    }

    public TaskExecutor(){
        this(corePoolSize,maximumPoolSize,keepAliveTime);
    }

    public TaskExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime){
        this.queue = new LinkedBlockingQueue<>();
        this.executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);
        this.executor.allowCoreThreadTimeOut(true);
    }

    public  void execute (Runnable task) {
        this.executor.execute(task);
    }
    /**
     * 获取队列数
     * @return
     */
    public int getQueueSize(){
        return this.queue.size();
    }

}
